package com.bjpowernode.shop.listener;

import com.alibaba.fastjson.JSON;
import com.bjpowernode.shop.constants.QueueConstants;
import com.bjpowernode.shop.domain.SmsMessage;
import com.bjpowernode.shop.utils.SmsUtils;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class ReceiveSmsListener {
    
    @Autowired
    private SmsUtils smsUtils;

    @RabbitListener(queues = {QueueConstants.PHONE_SMS_QUEUE})
    public void receiveSmsQueue(Message message, Channel channel) {

        // 获取消息队列中接收到的消息
        String json = new String(message.getBody());
        // 转换为实体类对象
        SmsMessage smsMessage = JSON.parseObject(json, SmsMessage.class);
        System.out.println("smsMessage = " + smsMessage);

        // 发送短信
        // smsUtils.sendSms(smsMessage);

        // 手动消费消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            try {
                // 如果消费失败，则清空队列
                channel.queuePurge(QueueConstants.PHONE_SMS_QUEUE);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
